package com.lagou.controller;

import com.lagou.pojo.Article;
import com.lagou.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/index")
    public String toIndex(String pageNumber,Model model){
        String spPage =pageNumber;
        //设置每页条数
        int pageSize =3;
        //页数
        int pageNo =0;
        if (spPage ==null){
            pageNo=1;
        }else {
            pageNo =Integer.valueOf(spPage);
            if (pageNo <1){
                pageNo=1;
            }
        }
        //设置最大页数
        int totalCount =0;
        int count =articleService.getArticleCount();
        if (count >0){
            totalCount =count;
        }
        int maxPage =totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
        if (pageNo >maxPage){
            pageNo=maxPage;
        }

        int tempPageNo =(pageNo-1)*pageSize;
        //分页查询
        Map map = new HashMap();
        map.put("pageNo",tempPageNo);
        map.put("pageSize",pageSize);
        List<Article> list =articleService.pageList(map);
        //List<Article> all = articleService.findAll();

        //最后把信息放入model转发到页面把信息带过去
        model.addAttribute("articleList",list);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("maxPage",maxPage);

        return "index";
    }
}
